<template>
  <el-dialog :visible="showDialog" :title="`${id?'修改':'添加'}权限`" @close="close" @opened="open">
    <el-form ref="form" label-width="100px" :model="formData" :rules="rules">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item label="权限启用">
        <el-switch
          v-model="formData.enVisible"
          active-text="启用"
          active-value="1"
          inactive-text="不启用"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: right;">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addPermissionAPI, getPermissionDetailAPI, updatePermissionAPI } from '@/api'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    value: {
      type: Object,
      default: () => {}
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        type: '', // 类型
        pid: '', // 添加到哪个节点下
        enVisible: '0' // 开启
      },
      rules: {
        name: { required: true, message: '姓名不能为空', trigger: 'blur' },
        code: { required: true, message: '权限标识不能为空', trigger: 'blur' },
        description: { required: true, message: '描述不能为空', trigger: 'blur' }
      }
    }
  },
  methods: {
    close() {
      this.$emit('close')
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        type: '', // 类型
        pid: '', // 添加到哪个节点下
        enVisible: '0' // 开启
      }
      this.$emit('update')
    },
    async open () {
      this.formData.pid = this.value.pid
      this.formData.type = this.value.type
      if (this.id) {
        try {
          const res = await getPermissionDetailAPI(this.id)
          this.formData = res.data
        } catch (err) {
          console.log(err)
        }
      }
    },
    async confirm() {
      try {
        await this.$refs.form.validate()
        if (this.id) {
          const res = await updatePermissionAPI(this.formData)
          this.$message.success(res.message)
        } else {
          const res = await addPermissionAPI(this.formData)
          this.$message.success(res.message)
        }
        this.close()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
